package com.example.c_reflect;

import java.lang.reflect.Field;

public class DemoTestFields {
    public static void main(String[] args) throws NoSuchFieldException, InstantiationException, IllegalAccessException {
        Class<Student> studentClass = Student.class;
        Field[] fields = studentClass.getFields();
        for (Field field : fields) {
            System.out.println(field + "====>" + field.getName());
        }

        System.out.println("===========================");
        Field[] declaredFields = studentClass.getDeclaredFields();
        for (Field declaredField : declaredFields) {
            System.out.println(declaredField);
        }

        System.out.println("===========================");
        Student student = studentClass.newInstance();
        Field age = studentClass.getField("age");
//        为属性进行赋值
        age.set(student, 10);
        age.get(student);
        System.out.println("age: " + age.get(student));

        System.out.println("===========================");
        Field name = studentClass.getDeclaredField("name");
        name.setAccessible(true);
        name.set(student, "张三");
        Object o = name.get(student);
        System.out.println("name: " + o);
    }
}
